<?php

namespace app\superpartner\controller;

use app\common\controller\CommonService;
use think\console\output\Question;
use think\Controller;
use think\Db;
use think\Request;

class Members extends Controller
{
    /**
     *超级合伙人会员列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function membersList(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $db = Db::name('user_manage')
            ->where('super_partner_id',$superPartnerId);
        if (!empty($requestData['nickname'])) {
            $db = $db->where('xingming|nickname', $requestData['nickname']);
        }
        if (!empty($requestData['code'])) {
            $db = $db->where('code', $requestData['code']);
        }
        if (!empty($requestData['tel'])) {
            $db = $db->where('tel', $requestData['tel']);
        }
        if (!empty($requestData['register_start']) && !empty($requestData['register_end'])) {
            $db = $db->whereBetween('time', [$requestData['register_start'],$requestData['register_end']]);
        }
        if (!empty($requestData['last_login_start']) && !empty($requestData['last_login_end'])) {
            $db = $db->whereBetween('last_login_time', [strtotime($requestData['last_login_start']), strtotime($requestData['last_login_end'])]);
        }
        if (!empty($requestData['tb_openid'])) {
            if ($requestData['tb_openid'] == 1) {
                $db = $db->whereNotNull('tb_openid');
            } else {
                $db = $db->whereNull('tb_openid');
            }
        }
        if (!empty($requestData['alipay_id'])) {
            if ($requestData['alipay_id'] == 1) {
                $db = $db->whereNotNull('alipay_id');
            } else {
                $db = $db->whereNull('alipay_id');
            }
        }
        if (!empty($requestData['is_vip'])) {
            if ($requestData['is_vip'] == 1) {
                $db = $db->where('is_vip', 'NEQ', 0);
            } else {
                $db = $db->where('is_vip', 0);
            }
        }
        //推荐人邀请码
        if (!empty($requestData['par_code'])) {
            $parId = Db::name('user_manage')->where('code',$requestData['par_code'])->value('id');
            $db = $db->where('par_id', $parId);
        }
        //合伙人邀请码
        if (!empty($requestData['partner_code'])) {
            $partnerId = Db::name('user_manage')->where('code',$requestData['partner_code'])->value('id');
            $db = $db->where('partner_id', $partnerId);
        }
        if (!empty($requestData['order_type']) && !empty($requestData['sort_type'])) {
            $db = $db->order($requestData['order_type'], $requestData['sort_type']);
        } else {
            $db = $db->order('id', 'desc');
        }
        $date['total_num'] = $db->count();
        $data['data'] = $db->page(input('page', 1), input('limit', 20))->select();
        //淘宝有效订单
        $tb_order = db('tb_order')
            ->where('order_status', 'NEQ', 0)
            ->where('order_type', 1)
            ->where('is_weiquan', 0)
            ->where('uid', 'NEQ', '')
            ->group('uid')
            ->column('uid,count(id)');
        //京东有效订单
        $jd_order = db('jd_order')
            ->where('order_status', 'NEQ', 0)
            ->where('uid', 'NEQ', '')
            ->group('uid')
            ->column('uid,count(id)');
        //拼多多有效订单
        $pdd_order = db('pdd_order')
            ->where('order_status', 'NEQ', 0)
            ->where('uid', 'NEQ', '')
            ->group('uid')
            ->column('uid,count(id)');
        //邀请好友数
        $invite_num = db('huodong_order')
            ->where('status', 1)
            ->where('par_id', 'NEQ', '')
            ->group('par_id')
            ->column('par_id,count(id)');
        //可用红包数
        $hongbao_num = db('hongbao')
            ->where('is_use', 0)
            ->where('uid', 'NEQ', '')
            ->group('uid')
            ->column('uid,sum(hongbao_money)');
        foreach ($data['data'] as $k => $v){
            $date['data'][$k]['headimgurl'] = $v['headimgurl'];
            $date['data'][$k]['nickname'] = CommonService::emoji_decode($v['nickname']) ? CommonService::emoji_decode($v['nickname']) : '';
            $date['data'][$k]['tel'] = $v['tel'];
            $date['data'][$k]['code'] = $v['code'];
            $date['data'][$k]['last_login_time'] = $v['last_login_time'];
            $date['data'][$k]['time'] = $v['time'];
            $date['data'][$k]['tb_openid'] = empty($v['tb_openid']) ? '否' : '是';
            $date['data'][$k]['alipay_id'] = empty($v['alipay_id']) ? '否' : '是';
            $date['data'][$k]['is_vip'] = empty($v['alipay_id']) ? '否' : '是';
            $date['data'][$k]['money'] = $v['money'];
            $date['data'][$k]['jifen'] = $v['jifen'];

            $date['data'][$k]['hongbao_num'] = isset($hongbao_num[$v['id']]) ? $hongbao_num[$v['id']] : 0;
            $tb_num = isset($tb_order[$v['id']]) ? $tb_order[$v['id']] : 0;
            $jd_num = isset($jd_order[$v['id']]) ? $jd_order[$v['id']] : 0;
            $pdd_num = isset($pdd_order[$v['id']]) ? $pdd_order[$v['id']] : 0;
            $date['data'][$k]['order_num'] = $tb_num + $jd_num + $pdd_num;
            $date['data'][$k]['invite_num'] = isset($invite_num[$v['id']]) ? $invite_num[$v['id']] : 0;

            $parInfo = Db::name('user_manage')->where('id',$v['par_id'])->field('nickname,code')->find();
            $date['data'][$k]['par_name'] = CommonService::emoji_decode($parInfo['nickname']) ? CommonService::emoji_decode($parInfo['nickname']) : '';
            $date['data'][$k]['par_code'] = $parInfo['code'];

            $uid = Db::name('partner')->where('id',$v['partner_id'])->value('uid');
            $partnerInfo = Db::name('user_manage')->where('id',$uid)->field('nickname,code')->find();
            $date['data'][$k]['partner_nickname'] = CommonService::emoji_decode($partnerInfo['nickname']) ? CommonService::emoji_decode($partnerInfo['nickname']) : '';
            $date['data'][$k]['partner_code'] = $partnerInfo['code'];

        }
        return CommonService::success($date);
    }

    /**
     *邀请记录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function inviteList(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $db = Db::name('huodong_order')
            ->alias('h')
            ->join('user_manage u', 'u.id = h.par_id', 'LEFT')
            ->join('user_manage b', 'b.unionid = h.unionid', 'LEFT')
            ->where('h.type',1)
            ->where('u.super_partner_id','in', $superPartnerId);
        if (!empty($requestData['nickname'])) {
            $db = $db->where('h.nickname', $requestData['nickname']);
        }
        if (!empty($requestData['par_name'])) {
            $parId = Db::name('user_manage')->where('nickname|xingming',$requestData['par_name'])->value('id');
            $db = $db->where('h.par_id', $parId);
        }
        if (!empty($requestData['par_code'])) {
            $parId = Db::name('user_manage')->where('code',$requestData['par_code'])->value('id');
            $db = $db->where('h.par_id', $parId);
        }
        if (!empty($requestData['invite_start']) && !empty($requestData['invite_end'])) {
            $db = $db->whereBetween('h.time', [strtotime($requestData['invite_start']), strtotime($requestData['invite_end'])]);
        }
        if (!empty($requestData['invite_status'])) {
            if ($requestData['invite_status'] == -1){
                $db = $db->where('h.status', 0);
            }
            if ($requestData['invite_status'] == 1) {
                $db = $db->where('h.status','<>', 0);
            }
        }
        if (!empty($requestData['register_start']) && !empty($requestData['register_end'])) {
            $db = $db->whereBetween('b.time', [$requestData['register_start'], $requestData['register_end']]);
        }
        if (!empty($requestData['order_type']) && !empty($requestData['sort_type'])) {
            $db = $db->order($requestData['order_type'], $requestData['sort_type']);
        } else {
            $db = $db->order('h.time', 'desc');
        }
        $date['total_num'] = $db->count();
        $data['data'] = $db->field('h.headimgurl,h.nickname,u.nickname as par_name,u.code as par_code,h.time as invite_time,h.status as invite_status,b.time as register_time')
            ->page(input('page', 1), input('limit', 20))
            ->select();
        foreach ($data['data'] as $k => $v) {
            $date['data'][$k]['headimgurl'] = $v['headimgurl'];
            $date['data'][$k]['nickname'] = CommonService::emoji_decode($v['nickname']);
            $date['data'][$k]['par_name'] = CommonService::emoji_decode($v['par_name']);
            $date['data'][$k]['par_code'] = $v['par_code'];
            $date['data'][$k]['invite_time'] = $v['invite_time'];
            $date['data'][$k]['time'] = $v['register_time'];
            switch ($v['invite_status']) {
                case 0:
                    $date['data'][$k]['invite_status'] = '邀请中';
                    break;
                case 1:
                    $date['data'][$k]['invite_status'] = '邀请成功';
                    break;
                case 2:
                    $date['data'][$k]['invite_status'] = '邀请超时';
                    break;
            }
        }
        return CommonService::success($date);
    }

    /**
     * 会员大数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function memberBigData(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $intervalStart = $requestData['now_start_time'];
        $intervaleEnd = $requestData['now_end_time'];
        $numTime = strtotime($intervaleEnd) - strtotime($intervalStart);
        $num = floor($numTime / 86400);
        //新增会员
        $new = [];
        for ($i = 0; $i <= $num; $i++) {
            $startNewTime = date('Y-m-d H:i:s', strtotime('+' . $i . ' days', strtotime($intervalStart)));
            $endNewTime = date('Y-m-d H:i:s', strtotime('+' . $i + 1 . ' days', strtotime($intervalStart)));
            $new[$i]['total_num'] = $this->getNewMerber($startNewTime, $endNewTime, $superPartnerId);
            $new[$i]['day'] = date('m-d', strtotime('+' . $i . ' days', strtotime($intervalStart)));
        }
        $data['user_new'] = $new;
        //累计会员
        $lei = [];
        for ($i = 0; $i <= $num; $i++) {
            $endTime = date('Y-m-d H:i:s', strtotime('+' . $i + 1 . ' days', strtotime($intervalStart)));
            $lei[$i]['total_num'] = $this->getMerber($endTime, $superPartnerId);
            $lei[$i]['day'] = date('m-d', strtotime('+' . $i . ' days', strtotime($intervalStart)));
        }
        $data['user_last'] = $lei;

        //会员等级
        $userLevel[0]['type'] = 'VIP';
        $vipNum = db('user_manage')->where('super_partner_id', $superPartnerId)->where('is_vip',  1)->count();
        $xVipNum = db('user_manage')->where('super_partner_id', $superPartnerId)->where('is_vip',  '>',time())->count();
        $userLevel[0]['total_num'] = $vipNum + $xVipNum;
        $userLevel[1]['type'] = '普通';
        $noVipNum = db('user_manage')->where('super_partner_id', $superPartnerId)->where('is_vip', 0)->count();
        $noXNum = db('user_manage')->where('super_partner_id', $superPartnerId)->whereBetween('is_vip',  [$intervalStart,time()])->count();
        $userLevel[1]['total_num'] = $noVipNum + $noXNum;
        $data['user_level']= $userLevel;

        //会员性别
        $userSex = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->field('sex,count(id) as total_num')
            ->group('sex')
            ->select();
        foreach ($userSex as $key => $value) {
            if ($value['sex'] == 1) {
                $userSex[$key]['sex'] = '男';
            } else if ($value['sex'] == 2) {
                $userSex[$key]['sex'] = '女';
            } else {
                $userSex[$key]['sex'] = '未知';
            }
        }
        $data['user_sex'] = $userSex;

        //会员职业
        $data['user_pro'][0] = $this->getZhiYeNum('BOSS',$superPartnerId);
        $data['user_pro'][1] = $this->getZhiYeNum('全职太太',$superPartnerId);
        $data['user_pro'][2] = $this->getZhiYeNum('公务员',$superPartnerId);
        $data['user_pro'][3] = $this->getZhiYeNum('学生',$superPartnerId);
        $data['user_pro'][4] = $this->getZhiYeNum('白领',$superPartnerId);
        $data['user_pro'][5] = $this->getZhiYeNum('其他',$superPartnerId);
        $data['user_pro'][6] = $this->getZhiYeNum('Null',$superPartnerId);
        $data['user_pro'][6]['zhiye'] = '未知';

        //会员生日
        $data['user_year'][0]['type'] = ' 0-20';
        $data['user_year'][1]['type'] = '20-29';
        $data['user_year'][2]['type'] = '30-39';
        $data['user_year'][3]['type'] = '40-49';
        $data['user_year'][4]['type'] = '50-60';
        $data['user_year'][5]['type'] = ' > 60';
        $data['user_year'][6]['type'] = '未知';
        $data['user_year'][0]['total_num'] = $this->getYearNum(0,20,$superPartnerId);
        $data['user_year'][1]['total_num'] = $this->getYearNum(20,29,$superPartnerId);
        $data['user_year'][2]['total_num'] = $this->getYearNum(30,39,$superPartnerId);
        $data['user_year'][3]['total_num'] = $this->getYearNum(40,49,$superPartnerId);
        $data['user_year'][4]['total_num'] = $this->getYearNum(50,59,$superPartnerId);
        $sixNum = $this->getYearNum(00,60,$superPartnerId);
        $sixNumNew = Db::name('user_manage')->where('super_partner_id', $superPartnerId)->where('shengri', '<>','Null')->count();
        $data['user_year'][5]['total_num'] = $sixNumNew - $sixNum;
        $data['user_year'][6]['total_num'] = Db::name('user_manage')->where('super_partner_id', $superPartnerId)->where('shengri', 'Null')->count();


        //省份分布
        $userProvince = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->field('register_province,count(id) as total_num')
            ->group('register_province')
            ->select();
        $data['user_province'] = $userProvince;
        foreach ($data['user_province'] as $k=>$v){
            if (strpos($data['user_province'][$k]['register_province'], '省') !== false){
                $data['user_province'][$k]['register_province'] = str_replace("省","",$v['register_province']);
            }
            if (strpos($data['user_province'][$k]['register_province'], '市') !== false){
                $data['user_province'][$k]['register_province'] = str_replace("市","",$v['register_province']);
            }
        }
        //城市分布
        $cityData = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->field('register_city as city,count(id) as total_num')
            ->group('register_city');
        $city = isset($requestData['city']) ? $requestData['city'] : '';
        if (!empty($city)) {
            if ($city != '全国'){
                $cityData = $cityData->where('register_province', $city);
            }
        }
        $data['user_city'] = $cityData->select();
        return CommonService::success($data);
    }

    /*获取累计注册会员
     *end_time 时间
     * */
    public function getMerber($endTime, $superPartnerId)
    {
        $userLast = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->where('time', '<', $endTime)
            ->count();
        return $userLast;
    }
    /*
     * 获取新增注册会员
     * */
    public function getNewMerber($startTime, $endTime, $superPartnerId)
    {
        $userLast = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->whereBetween('time', [$startTime,$endTime])
            ->count();
        return $userLast;
    }
    /*
     * 获取职业数据
     * */
    public function getZhiYeNum($zhiye, $superPartnerId = null)
    {
        if (empty($superPartnerId)) \request()->superPartnerId;
        $num = Db::name('user_manage')
            ->where('super_partner_id',$superPartnerId)
            ->where('zhiye',$zhiye)
            ->count();
        $data['zhiye'] = $zhiye;
        $data['total_num'] = $num;
        return $data;
    }
    /*获取年龄段人数
     * */
    public function  getYearNum($startY, $endY, $superPartnerId)
    {
        $startYears = date('Y-m-d', strtotime('-' . $startY . ' years', time()));
        $endYears = date('Y-m-d', strtotime('-' . $endY . ' years', time()));
        $userYear = Db::name('user_manage')
            ->where('super_partner_id', $superPartnerId)
            ->whereBetween('shengri', [$endYears,$startYears])
            ->count();
        return $userYear;
    }
}